package org.foreveross.que.infra.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.foreveross.que.entity.SayEntity;
import org.foreveross.que.infra.SayRepository;
import org.foreveross.que.infra.base.ddd.repository.EntityHibernateRepository;
import org.springframework.stereotype.Repository;

@Repository
public class SayRepositoryImpl extends EntityHibernateRepository implements
		SayRepository {

	private static final String alias = "t";
	
	private static final String FIND_SUBJECT_SQL = "from SayEntity t where t.state = 1 and 1=1 ";

	private static final String FIND_SUBJECT_COUNT_SQL = "select count(t) from SayEntity t where t.state = 1 and 1=1 ";

	/**
	 * 根据条件分页查询记录
	 * 
	 * @param params
	 * @param pageIndex
	 * @param pageLen
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<SayEntity> findSays(Map<String, Object> paramsMap, Integer pageIndex,
			Integer pageLen) throws Exception {
		String queryStr = FIND_SUBJECT_SQL;
		Object [] arr = this.generateHqlByConditions(paramsMap, alias);
		queryStr += arr[0].toString();
		queryStr += " order by t.lastTime desc";
		Object [] params = (Object [])arr[1];
		return super.queryResult(queryStr, params, pageIndex, pageLen);
	}

	/**
	 * 根据条件查询记录总数
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public Long findSaysCount(Map<String, Object> paramsMap) throws Exception {
		String queryStr = FIND_SUBJECT_COUNT_SQL;
		Object [] arr = this.generateHqlByConditions(paramsMap, alias);
		queryStr += arr[0].toString();
		Object [] params = (Object [])arr[1];
		return super.queryResultSize(queryStr, params);
	}

	private Object[] generateHqlByConditions(Map<String, Object> paramsMap,
			String alias) {
		Object[] finalResult = new Object[2];
		StringBuffer queryStr = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		if (paramsMap != null && paramsMap.size() != 0) {
			for (String key : paramsMap.keySet()) {
				Object value = paramsMap.get(key);
				if (value == null) {
					continue;
				}
				if (value instanceof String) {
					if (StringUtils.isBlank(value.toString())) {
						continue;
					} else {
						value = StringUtils.trim((String) value);
					}
				}
				queryStr.append(" and ").append(alias).append(".").append(key);
				queryStr.append("=?");

				params.add(value);
			}
		}

		finalResult[0] = queryStr;
		finalResult[1] = params.toArray();
		return finalResult;
	}

}
